import { defineStore } from "pinia";
import { ref, reactive, getCurrentInstance, onMounted } from "vue";
import socket from "./socket"
export const useUserStore = defineStore("user", () => {
    let alluser = ref([])        // 存储所有用户信息
    let pendingRequests = ref([])  // 存储未处理的好友请求
    // 获取全局 axios 实例
    const app = getCurrentInstance();
    const axios = app?.proxy?.$axios;
    let userId = "67453ffb19fa82ef5441cca2"   //暂时定义一个死的本地存储当前登录用户id

    // 监听来自服务器的好友请求变更
    socket.on("friendRequest", (notification) => {
        console.log("你收到一个新的好友请求", notification)
        pendingRequests.value.push(notification)
    })

    // 获取所有未添加的用户
    async function getAllUser(value) {  //value是用户名
        const { data: { code, data } } = await axios.post("/getOneUser", { username: value, userID: userId })
        if (code === 200) {
            alluser.value = data
        } else {
            alluser.value = []
        }
        console.log(data)
    }

    // 发送好友请求
    async function sendFriendRequest(value) {    //value是用户id
        let res = await axios.post("/sendFriend", { userID: userId, friendID: value })
        console.log(res)
        socket.emit("sendFriendRequest", { userID: userId, friendID: value })
    }

    // 获取未处理的好友请求
    async function getPendingFriendRequests() {
        const { data: { code, data } } = await axios.post("/getPendingRequests", { userID: userId })
        if (code === 200) {
            // 设置当前用户的未处理好友请求
            pendingRequests.value = data
        } else {
            pendingRequests.value = []
        }
    }

    // 在组件挂载时调用获取未处理请求的接口
    onMounted(() => {
        getPendingFriendRequests()   //用户上线时，加载未处理的请求
    })

    return {
        alluser, pendingRequests,
        getAllUser, sendFriendRequest, getPendingFriendRequests
    }
});